package tgc.edu.tms.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.tms.custom.AjaxResult;
import tgc.edu.tms.custom.CommonController;
import tgc.edu.tms.custom.ExportExcel;
import tgc.edu.tms.custom.ImportExcel;
import tgc.edu.tms.custom.TablePageable;
import tgc.edu.tms.custom.TimeUtils;
import tgc.edu.tms.entity.ClassType;
import tgc.edu.tms.entity.Curriculum;
import tgc.edu.tms.entity.EducationalPlanner;
import tgc.edu.tms.entity.Profession;
import tgc.edu.tms.entity.Schoolyear;
import tgc.edu.tms.entity.TbClass;
import tgc.edu.tms.entity.Teacher;
import tgc.edu.tms.service.ClassTypeService;
import tgc.edu.tms.service.CurriculumService;
import tgc.edu.tms.service.EducationalPlannerService;
import tgc.edu.tms.service.ProfessionService;
import tgc.edu.tms.service.SchoolyearService;
import tgc.edu.tms.service.TbClassService;
import tgc.edu.tms.service.TeacherService;
import tgc.edu.tms.web.form.EducationalPlannerForm;
@Controller
@RequestMapping(value="/ep")
public class EducationalPlannerController extends CommonController<EducationalPlanner, Integer, EducationalPlannerForm>{
	@Autowired
	private ProfessionService pservice;//学年 学院 专业
	@Autowired
	private SchoolyearService schoolservice;//学院学期
	@Autowired
	private EducationalPlannerService epservice;//课程录入表
	@Autowired
	private CurriculumService cuservice;
	@Autowired
	private TeacherService teacherservice;
	@Autowired
	private  ClassTypeService typeservice;
	@Autowired
	private TbClassService tbclassServcie;
	
	
	@Override
	public Object page(TablePageable pageParam, EducationalPlannerForm form) {
		PageRequest pageable = pageParam.bulidPageRequest();
		Specification<EducationalPlanner> spec = buildSpec(form);
		Page<EducationalPlanner> page=epservice.findAll(spec, pageable);
		return AjaxResult.bulidPageResult(page);
	}

	@Override
	public void manage(ModelMap map) {
		List<String> year = pservice.findAllYear();
		map.put("years", year);
	}

	@Override
	public void edit(EducationalPlannerForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		List<String> year = pservice.findAllYear();
		List<Teacher> teacher = teacherservice.findAll();
		List<ClassType> list = typeservice.findAll();
		map.put("years", year);
		map.put("teacher", teacher);
		map.put("jslx", list);
		if(form.getId()!=null) {
			EducationalPlanner ep = epservice.findById(form.getId());
		    map.put("model", ep);
		}
	}
	
	@RequestMapping(value="/getCollege")
	@ResponseBody
	private Object getcollege(String year) {
		List<String> college = pservice.findCollegeByYear(year);
		return college;
	}
	
	@RequestMapping(value="/getProfesion")
	@ResponseBody
	private Object getprofesion(String year,String college) {
		return pservice.findByYearAndCollege(year,college);
	}
	@RequestMapping(value="/getBanji")
	@ResponseBody
	private Object getBanji(String year,String college,String profesion) {
		Profession profession = pservice.findByYearAndCollegeAndProfesion(year, college, profesion);
		return tbclassServcie.findByprofessionID(profession.getId()); 
	}
	@RequestMapping(value="/findQszc")
	@ResponseBody
	private Object findQszc(Integer ids) {
		Curriculum curriculum = cuservice.findById(ids);
		Integer zongxs = curriculum.getZongxs();
		Integer zhouxs = curriculum.getZhouxs();
		Integer sun=0;
		sun=zongxs/zhouxs;
		if(sun*zhouxs<zongxs) {
			sun=sun+1;
		}
		return sun; 
	}
	@RequestMapping(value="/getKc")
	@ResponseBody
	private Object getkc(String year,String college,String profesion,Integer xnxq) {
		
		Profession profession = pservice.findByYearAndCollegeAndProfesion(year, college, profesion);
		Schoolyear schoolyear = schoolservice.findById(xnxq);
		String a[]= {"一","二","三","四","五","六"};
		String kkxqs[] = TimeUtils.Getcurrentsemester(profession,schoolyear,a);
		List<Curriculum> curr=cuservice.findByKkxqAndProfessionId(kkxqs[0],profession.getId());
		return curr; 
	}
	@RequestMapping(value="/getXnxq")
	@ResponseBody
	private Object getXnxq(String year) throws ParseException{
		Integer years=Integer.parseInt(year);//第一年
        Integer years2=years+1;//第二年
        Integer years3=years2+1;//第三年
        Integer years4=years3+1;//第四年
        List<Schoolyear> sc=null;
        Specification<Schoolyear> spec = new Specification<Schoolyear>() {
			@Override
			public Predicate toPredicate(Root<Schoolyear> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				HashSet<Predicate> rules = new HashSet<>();
				Predicate predicate=null;
				rules.add(criteriaBuilder.like(root.get("xnxq"), years+"年秋季学期"+"%"));
				
				rules.add(criteriaBuilder.like(root.get("xnxq"), years2+"%"));
				
				rules.add(criteriaBuilder.like(root.get("xnxq"), years3+"%"));
				
				rules.add(criteriaBuilder.like(root.get("xnxq"), years4+"年春季学期"+"%"));
				
				predicate=criteriaBuilder.or(rules.toArray(new Predicate[rules.size()]));
				return predicate;
			}
		};
		Sort sort = new Sort(Sort.Direction.DESC, "id");
        sc=schoolservice.findAll(spec,sort); 
		return sc;
	}
    /***
     * 保存
     */
	@Override
	public Object save(EducationalPlannerForm form) {
		try {
			EducationalPlanner model=new EducationalPlanner(); 
			Integer id = form.getId();
			if(id!=null) {
				model=epservice.findById(id);
				model.getTbclass().clear();
			}
			BeanUtils.copyProperties(form, model,"id","teacher","kcid","xnxqid"," banji");
			Integer teacherid = form.getTeacher();
			Teacher teacher = teacherservice.findById(teacherid);
			model.setTeacher(teacher);
			Integer kcid = form.getKcid();
			Curriculum curriculum = cuservice.findById(kcid);
			model.setCurriculum(curriculum);
			Integer xnxqid = form.getXnxqid();
			Schoolyear schoolyear = schoolservice.findById(xnxqid);
			model.setSchoolyear(schoolyear);
			List<Integer> banji = form.getBanji();
			String str="";
			for (Integer tbclassid : banji) {
				TbClass tbClass = tbclassServcie.findById(tbclassid);
				model.getTbclass().add(tbClass);
				str +=tbClass.getName()+",";
			}
			str=str.substring(0,str.length()-1);
			model.setSearcherbanji(str);
			epservice.save(model);
			return new AjaxResult("OK");
		}catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}
	}

	@Override
	public Specification<EducationalPlanner> buildSpec(EducationalPlannerForm form) {
		Specification<EducationalPlanner> spec = new Specification<EducationalPlanner>() {
            
			@Override
			public Predicate toPredicate(Root<EducationalPlanner> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
				List<Predicate> rules = new ArrayList<>();
				if (StringUtils.hasText(form.getYear())) {
					rules.add(cb.like(root.get("curriculum").get("profession").get("year"),"%" + form.getYear() + "%"));
				}
				if (StringUtils.hasText(form.getCollege())) {
					rules.add(cb.like(root.get("curriculum").get("profession").get("college"), "%" + form.getCollege() + "%"));
				}
				if (StringUtils.hasText(form.getProfesion())) {
					rules.add(cb.like(root.get("curriculum").get("profession").get("profesion"),"%" + form.getProfesion() + "%"));
				}
				if (StringUtils.hasText(form.getSearcherbanji())) {
					String string = form.getSearcherbanji();
					Integer a= Integer.parseInt(string);
					TbClass tbClass = tbclassServcie.findById(a);
					rules.add(cb.like(root.get("searcherbanji"),"%" + tbClass.getName() + "%"));
				}
				if (StringUtils.hasText(form.getSearch())) {
					Predicate kcmcname = cb.like(root.get("curriculum").get("kcmc"),"%" + form.getSearch() + "%");
					Predicate kcdm = cb.like(root.get("curriculum").get("kcdm"),"%" + form.getSearch() + "%");
					Predicate schoolyear = cb.like(root.get("schoolyear").get("xnxq"),"%" + form.getSearch() + "%");
					Predicate banji = cb.like(root.get("searcherbanji"),"%" + form.getSearch() + "%");
					Predicate teacher = cb.like(root.get("teacher").get("name"),"%" + form.getSearch() + "%");
					Predicate xy = cb.like(root.get("curriculum").get("profession").get("college"),"%" + form.getSearch() + "%");
					Predicate zy = cb.like(root.get("curriculum").get("profession").get("profesion"),"%" + form.getSearch() + "%");
					Predicate jslx = cb.like(root.get("jslx"),"%" + form.getSearch() + "%");
					Predicate rules2 = cb.or(kcmcname,kcdm,schoolyear,teacher,xy,zy,jslx,banji);
					rules.add(rules2);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	

	
	/**
     * 导出报表
	 * @return
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	List<EducationalPlanner> list = epservice.findAll();
    	String title = "教学计划";
        String[] columnName = new String[]{"序号","课程","课程代码","学分","学年学期","学院","课程类别","专业","班级","考核方式","总学时","周学时","教室类型","上课周次","上课老师"};
        List<Object[]> dataList = new ArrayList<Object[]>();
       
        for (EducationalPlanner e:list) {
        	  String kcmc = e.getKcmc();
        	  String kcdm = e.getKcdm();
        	  String teacherName = e.getTeachername();
        	  String xnxq = e.getXnxq();
        	  String xy = e.getXy();
        	  Integer zongxs = e.getZongxs();
        	  String bj = e.getBj();
        	  String jslx = e.getJslx();
        	  String skzc = e.getSkzc();
        	  Integer zhouxs = e.getZhouxs();
        	  String zy = e.getZy();
        	  Float xf = e.getXf();
        	  String kclb = e.getKclb();
        	  String khfs = e.getKhfs();
        	 Object[] objs = {
        			 kcmc,kcmc,kcdm,xf,xnxq,xy,kclb,zy,bj,khfs,zongxs,zhouxs,jslx,skzc,teacherName
        	 };
          
          
            
            dataList.add(objs);
        }
        //实例化工具类
        ExportExcel ex = new ExportExcel(title, columnName, dataList,request,response);
        try {
            //导出excel
            ex.export();
        } catch (Exception e) {
            e.printStackTrace();
        }
   }
	/**
     * 导出模板
     * @return
     */
    @RequestMapping(value = "/exportmoban")
    @ResponseBody
    public void exportmoban(HttpServletRequest request,HttpServletResponse response) throws Exception {
    	String title = "教学计划导入模板";
    	String[] columnName = new String[]{"序号","课程","课程代码","年级","学年学期","学院","专业","班级","教室类型","上课老师","起始周次","结束周次"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = {"1","专业英语","031051","2017","2017年秋季学期","电子信息学院","软件技术","软件一班/软件二班","普通教室","张老师","1","20"};
        dataList.add(objs);
        //实例化工具类
        ExportExcel ex = new ExportExcel(title, columnName, dataList,request,response);
        try {
            //导出excel
            ex.export();
        } catch (Exception e) {
            e.printStackTrace();
        }
   }
    /**
     * 导入报表
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "/excelimport")
    @ResponseBody
    public Object excelimport(MultipartFile file)throws IOException {
    	    try {
    	    	//实例化工具类
    			ImportExcel excelReader = new ImportExcel();
                InputStream is = file.getInputStream();
    	        //导入excel
    	    	excelReader.readExcelContent(is);
    	    	Map<Integer, String> map = excelReader.readExcelContent(is);
    	    	 is.close();
    	        //这里由于xls合并了单元格需要对索引特殊处理
    	        for (int i = 3; i <= map.size()+1; i++) {
    	        	int y=i+1;
    	            String[] scoreArray=map.get(i).split("-");
    	            System.out.println(map.get(i));
    	            String kcmc = scoreArray[1];
    	            String kcdm = scoreArray[2];
    	            String year = scoreArray[3];
    	            String xnxq = scoreArray[4];
    	            String college = scoreArray[5];
    	            String profesion = scoreArray[6];
    	            String bj = scoreArray[7];
    	            String jslx = scoreArray[8];
    	            String teacher = scoreArray[9];
    	            String qszc = scoreArray[10];
    	            String jszc = scoreArray[11];
    	            EducationalPlanner e=new EducationalPlanner();
    	            e.setQszc(qszc);
    	            e.setJszc(jszc);
    	            e.setJslx(jslx);
    	            Integer years=Integer.parseInt(year);//第一年
    	            Integer years2=years+1;//第二年
    	            Integer years3=years2+1;//第三年
    	            Integer years4=years3+1;//第四年
    	            String x[] = {years+"年秋季学期",years2+"年春季学期",years2+"年秋季学期",years3+"年春季学期",years3+"年秋季学期",years4+"年春季学期"}; 
                    Integer sum=0;
    	            for (int j = 0; j < x.length; j++) {
    				     String string = x[j];
    				      if (xnxq.equals(string)) {
    				    	 sum=1;
    						 break;
    					}
    			    }
                    if (sum==0) {
    					return "第"+y+"行学年学期不再年级安排范围内";
    				}
    	            Schoolyear schoolyear = schoolservice.findByXnxq(xnxq);
    	            if(schoolyear==null) {
    	            	return "第"+y+"行学年学期有误";	 
    	            }
    	            e.setSchoolyear(schoolyear);
    		        Teacher teacher2 = teacherservice.findByName(teacher);
    		        if(teacher2==null) {
    		        	return "第"+y+"行老师未找到,请在教师管理内添加!";
    		        }
    		        e.setTeacher(teacher2);
    		        Profession p = pservice.findByYearAndCollegeAndProfesion(year, college, profesion);
    		        Curriculum c=cuservice.findByKcmcAndKcdmAndProfession_id(kcmc,kcdm,p.getId());
    		        if (c==null) {
    					return "第"+y+"行课程未找到,请检查输入的年级,院系,专业是否对应!";
    				}
    		        e.setCurriculum(c);
    		        String[] a = bj.split("/");
    		        String str="";
    		        for (String banji : a) {
    					TbClass tbClass = tbclassServcie.findByProfessionIDAndtbclassName(p.getId(), banji);
    					if (tbClass==null) {
    						return "第"+y+"行班级未找到,请检查输入的年级,院系,专业是否对应!";
    					}
    					e.getTbclass().add(tbClass);
    					str += tbClass.getName();
    				}
    		        e.setSearcherbanji(str.substring(0, str.length()-1));
    		        epservice.save(e);
    		}
    	        return "导入成功";
			} catch (Exception e) {
				 return "导入失败";
			}
     }
}